#!/usr/bin/env python
# Simple INI file reader, expecting "xxxxx = yyyy" type of input
# [xxxxx] type of sections supported

import sys
import re

class IniReader:
    def __init__(self, filename=None, initConfigs={}, data="", debug=0):
        self._debug = debug
        self._data = ""

        if filename:
            self._data = open(filename, "r").readlines()
        elif data:
            self._data = data.split('\n')

        self.parse(initConfigs)

    def parse(self, initConfigs):
        current_section = "global"
        self._d = initConfigs
        if not self._d.has_key("global"):
            self._d["global"] = {}

        for line in self._data:
            # Ignore comments (starting with #)
            m = re.search("^\s*#", line)
            if m:
                continue

            # First find section
            m = re.search(r"^\[([^\[\]]+)\]", line)
            if m:
                current_section = m.group(1)
                if not self._d.has_key(current_section):
                    self._d[current_section] = {}
                continue

            pattern = re.compile(r"^\s*([^=]+?)\s*=\s*(.*)\s*", re.IGNORECASE)
            m = re.search(pattern, line)
            if m:
                self._d[current_section][m.group(1)] = m.group(2).rstrip()

            if self._debug and line.strip():
                print "Unparsed line: %s" % line

    def __getitem__(self, key):
        "default to return global configs."
        if self._d["global"].has_key(key):
            return self._d["global"][key]
        else:
            return None

    def __setitem__(self, key, value):
        "default to set global configs."
        self._d["global"][key] = value

    def sections(self, key):
        return self._d[key]

if __name__ == '__main__':
    testdata = """
# This is global configs
a=
 x= 12 b   
y=2342 234 234 

  # This is section1 configs
[section1]
 a= b   
1.1 = 2342 234 234 
sdf asfd sadf asf = asdf asf asdf sadf asf    

[section2 sdf sdf ]     
 a2 = b    
        1.3 = 2342 234 234     
  sdfsdf as asfd sadf asf = asdf asf asdf sadf asf    

"""
    r = IniReader(data = testdata)
    print r["a"]
    print r["x"]
    print r["y"]
    print r["None"]

    print r.sections("section1")
    print r.sections("section2 sdf sdf ")
